/*
 *  @Title SqlSessionManagerDaoSupport.java
 *  @Package： com.phoenix.orm
 *  Copyright (c) 2017 by 江苏深南互联网金融信息服务有限公司  All right reserved
 */
package com.phoenix.orm;

import static org.springframework.util.Assert.notNull;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.dao.support.DaoSupport;

/**
 *  @ClassName SqlSessionManagerDaoSupport
 *  @Description 类注释
 *  @author liuwei
 *  @version 1.0
 *  @date 2017年4月18日
 */
public class SqlSessionManagerDaoSupport extends DaoSupport {

    private SqlSession sqlReaderSession;
   
    private boolean externalSqlReaderSession = Boolean.FALSE;

    private SqlSession sqlSession;

    private boolean externalSqlSession = Boolean.FALSE;
    
    /**
     * 写库
     */
	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
      if (!this.externalSqlSession) {
        this.sqlSession = new SqlSessionTemplate(sqlSessionFactory);
      }
    }

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
      this.sqlSession = sqlSessionTemplate;
      this.externalSqlSession = true;
    }

    /**
     * Users should use this method to get a SqlSession to call its statement methods
     * This is SqlSession is managed by spring. Users should not commit/rollback/close it
     * because it will be automatically done.
     *
     * @return Spring managed thread safe SqlSession
     */
    public SqlSession getSqlSession() {
      return this.sqlSession;
    }
    
    /**
     * 读库
     */
    @Override
    protected void checkDaoConfig() {
        notNull(this.sqlSession, "Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required");
        notNull(this.sqlReaderSession, "Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required");
    }
    
	public void setSqlReaderSessionFactory(SqlSessionFactory sqlReaderSessionFactory) {
	    if (!this.externalSqlReaderSession) {
	      this.sqlReaderSession = new SqlSessionTemplate(sqlReaderSessionFactory);
	    }
	}

	public void setSqlReaderSessionTemplate(SqlSessionTemplate sqlReaderSessionTemplate) {
	  this.sqlReaderSession = sqlReaderSessionTemplate;
	  this.externalSqlReaderSession = true;
	}

    public SqlSession getReaderSqlSession() {
	   return this.sqlReaderSession;
	}

}
